package com.sxt.system.controller;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import com.sxt.system.constast.Constast;
import com.sxt.system.domain.Dept;
import com.sxt.system.service.IDeptService;
import com.sxt.system.utils.DataGridView;
import com.sxt.system.utils.ResultObj;
import com.sxt.system.utils.TreeNode;
import com.sxt.system.vo.DeptVO;

/**
 * <p>
 *  前端控制器 部门管理
 * </p>
 *
 * @author 俊哥
 * @since 2019-11-11
 */
@RestController
@RequestMapping("dept")
public class DeptController {

	@Autowired
	private IDeptService deptService;
	
	private Log log = LogFactory.getLog(DeptController.class);
	
	/**
	 * 	全查询
	 */
	@RequestMapping("loadAllDept")
	public DataGridView loadAllDept(DeptVO deptVO) {
		return this.deptService.loadAllDept(deptVO);
	}
	
	/**
	 * 生成json树
	 */
	@RequestMapping("loadAllDeptTreeJson")
	public DataGridView loadAllDeptTreeJson(DeptVO deptVO) {
		deptVO.setAvailable(Constast.AVAILABLE_TRUE);//只查询可用
		List<Dept> allDept = this.deptService.queryAllDeptForList(deptVO);
	
		List<TreeNode> treeNodes = new ArrayList<>();
		for (Dept dept : allDept) {
			Integer id = dept.getId();
			Integer pid = dept.getPid();
			String title = dept.getTitle();
			Boolean spread = dept.getOpen()==1?true:false;
			treeNodes.add(new TreeNode(id, pid, title, spread));
		}
		return new DataGridView(treeNodes);
	}
	
	/**
	 * 	加载部门最大的排序码
	 */
	@RequestMapping("loadDeptMaxOrderNum")
	public DataGridView loadDeptMaxOrderNum() {
		Integer maxOrderNum = this.deptService.queryDeptMaxOrderNum();
		return new DataGridView(maxOrderNum+1);
	}
	
	/**
	 * 	添加
	 */
	@RequestMapping("addDept")
	public ResultObj addDept(Dept dept ,HttpSession session) {
		dept.setCreatetime(new Date());//设置时间
		try {
			deptService.addDept(dept);
			return ResultObj.ADD_SUCCESS;
		} catch (Exception e) {
			log.error("添加失败");
			return ResultObj.ADD_ERROR;
		}
	}
	
	/**
	 * 修改
	 */
	@RequestMapping("updateDept")
	public ResultObj updateDept(Dept dept) {
		try {
			deptService.updateDept(dept);
			return ResultObj.UPDATE_SUCCESS;
		} catch (Exception e) {
			log.error("修改失败");
			return ResultObj.UPDATE_ERROR;
		}
	}
	
	/**
	 * 	根据部门ID查询当前部门有多少子节点
	 */
	@RequestMapping("checkCurrentDeptHasChild")
	public DataGridView checkCurrentDeptHasChild(Integer id) {
		Integer count = this.deptService.queryDeptCountByPid(id);
		return new DataGridView(count);
	}
	
	/**
	 * 	删除
	 */
	@RequestMapping("deleteDept")
	public ResultObj deleteDept(Integer id) {
		try {
			deptService.removeById(id);
			return ResultObj.DELETE_SUCCESS;
		} catch (Exception e) {
			log.error("删除失败");
			return ResultObj.DELETE_ERROR;
		}
	}
	
}

